from bottle import request, response
from freepost import database, random, settings

# Start a new session
def start (user_id, remember = False):
    # Create a new token for this session.
    # The random token is stored as a user cookie, and its hash value is
    # stored in the database to match the current user for the future requests.
    session_token = random.ascii_string (64)
    
    # Create session cookie
    response.set_cookie (
        name     = settings['session']['name'],
        value    = session_token,
        secret   = settings['cookies']['secret'],
        path     = '/',
        # When to end the session
        max_age  = settings['session']['remember_me'] if remember else None,
        # HTTPS only
        secure   = False,
        # Do not allow JavaScript to read this cookie
        httponly = True)
    
    # Store session to database
    database.new_session (user_id, session_token)

# Close the current open session
def close ():
    session_user = user ()
    
    # Delete user cookie containing session token
    response.delete_cookie (settings['session']['name'])
    
    # Delete session token from database
    database.delete_session (session_user['id'])

# Retrieve user from session token
def user ():
    session_token = request.get_cookie (
        key    = settings['session']['name'],
        secret = settings['cookies']['secret'])
    
    if session_token is None:
        return None
    
    return database.get_user_by_session_token (session_token)
